//
//  LJCMusicViewController.m
//  WZLProduct
//
//  Created by 陆静聪 on 16/3/19.
//  Copyright © 2016年 HaiTeng. All rights reserved.
//

#import "LJCMusicViewController.h"

@interface LJCMusicViewController ()<getMusicUrlDelegate>

@property (nonatomic, retain) UIImageView *musicPic;

@property (nonatomic, retain) UISlider *progressSlider;
@property (nonatomic, retain) UILabel *timeLabel;
@property (nonatomic, assign) CGFloat totalDuration;

@property (nonatomic, retain) NSMutableArray *urlArr;

@property (nonatomic, assign) NSInteger index;

@property (nonatomic, retain) LJCDiscView *discView;

@end

@implementation LJCMusicViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self createProgress];
    
    [self createPlay];
    
    [self createDisc];
    
    [self createTime];

    [self createList];
    
    [self addProgressObserver];
    
    [self getTime];
    
    [LJCMusicPlay shareMusicPlayer].endBlock = ^void {
        if ([[NSUserDefaults standardUserDefaults] boolForKey:@"singleOrList"] == YES) {
            if ([LJCMusicPlay shareMusicPlayer].isPlay == NO) {
                
                if (_index < _urlArr.count - 1) {
                    _index = _index + 1;
                    [self playWhatMusic];
                } else {
                    _index = 0;
                    [self playWhatMusic];
                }
            } else {
                    [self playWhatMusic];
                NSLog(@"yes");
            }

            
        } else {
            NSLog(@"adada");
        
            [self playWhatMusic];

        }

    };
    

}
/** 创建列表 */
- (void)createList {
    UIBarButtonItem *listButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-liebiao.png"] style:UIBarButtonItemStylePlain target:self action:@selector(listAction:)];
    self.navigationItem.rightBarButtonItem = listButton;
}

- (void)listAction:(UIBarButtonItem *)list {
    LJCMusicListViewController *lVC = [[LJCMusicListViewController alloc] init];
    lVC.urlArr = _urlArr;
    lVC.index = _index;
    lVC.musicDelegate = self;
    [self.navigationController pushViewController:lVC animated:YES];
}
#pragma mark - music代理方法
- (void)playMusic:(NSIndexPath *)index {
    _index = index.row;
    [self playWhatMusic];
}

- (void)getURL:(NSString *)URL {
    LJCMusicModel *musicModel = _urlArr[_index];
    /** 背景和碟片图片 */
    [self blackGroundView:musicModel.imgUrl];
    [_discView getImage:musicModel.imgUrl];
    /** 放磁盘 */
    [LJCMusicPlay shareMusicPlayer].url = musicModel.musicUrl;
    /** 是否旋转 */
    [self isTransfer];
    
    LJCPlayerView *playButton = [self.view viewWithTag:2000];
    
    
    if ([LJCMusicPlay shareMusicPlayer].isPlay == NO) {
        [playButton.playButton setImage:[UIImage imageNamed:@"iconfont-zanting.png"] forState:UIControlStateNormal];
    } else {
        [playButton.playButton setImage:[UIImage imageNamed:@"iconfont-iconfontbofang.png"] forState:UIControlStateNormal];
    }

    
}

- (void)getUrlArr:(NSMutableArray *)urlArr indexPath:(NSInteger)index {
    if (_urlArr != urlArr) {
        _urlArr = urlArr;
    }
    _index = index;
    [self playWhatMusic];
}


/** 创建播放时间 */
- (void)createTime {
    _timeLabel = [[UILabel alloc] init];
    [self.view addSubview:_timeLabel];
    [_timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.bottom.mas_equalTo(-200);
        make.size.mas_equalTo(CGSizeMake(100, 15));
    }];
    _timeLabel.textColor = [UIColor whiteColor];
    _timeLabel.font = FONT12;
}

/** 创建播放按钮 */
- (void)createPlay {
    LJCPlayerView *playButton = [[LJCPlayerView alloc] init];
    [self.view addSubview:playButton];
    
    playButton.tag = 2000;
    [playButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(-20);
        make.centerX.equalTo(self.view.mas_centerX);
        make.height.mas_equalTo(50);
        make.left.right.offset(0);
    }];
    /** 下一首 */
    playButton.nextBlock = ^(void) {
        if (_index < _urlArr.count - 1) {
            _index = _index + 1;
            [self playWhatMusic];
        } else {
            _index = 0;
            [self playWhatMusic];
        }
    };
    /** 上一首 */
    playButton.priorBlock = ^(void) {
        if (_index > 0) {
            _index = _index - 1;
            [self playWhatMusic];
        }
        
    };
    
    playButton.discBlock = ^(void) {
        [self isTransfer];
    };
    
    playButton.moreBlock = ^(void) {
        LJCSetView *setView = [LJCSetView createSetView];
        
        [[UIApplication sharedApplication].keyWindow addSubview:setView];
        setView.timeBlock = ^void {
            LJCTimeViewController *TVC = [[LJCTimeViewController alloc] init];
            [self.navigationController pushViewController:TVC animated:YES];
        };
    };
    
}

/** 播放那首歌 */
- (void)playWhatMusic {
    LJCMusicModel *musicModel = _urlArr[_index];
    [self getURL:musicModel.musicUrl];
    [[LJCMusicSwitch shareMusicSwitch] getTitle:musicModel.title];
}


/** 创建进度条 */
- (void)createProgress {
    _progressSlider = [[UISlider alloc] init];
    [self.view addSubview:_progressSlider];
    [_progressSlider mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(80);
        make.right.offset(-80);
        make.bottom.offset(-150);
        make.height.mas_equalTo(20);
    }];
    _progressSlider.minimumTrackTintColor = [UIColor greenColor];
    _progressSlider.minimumValue = 0;
    _progressSlider.maximumValue = 1;
    
    [_progressSlider addTarget:self action:@selector(progressAction:) forControlEvents:UIControlEventValueChanged];
    
}
/** 选择在哪播放 */
- (void)progressAction:(UISlider *)slider {
    
    [[LJCMusicPlay shareMusicPlayer] pause];
    
    UISlider *progressSlider = slider;
    // 获取到当前进度时间
    CGFloat currentTime = self.totalDuration * progressSlider.value;
    // 转化为CMTime
    CMTime dragTime = CMTimeMake(currentTime, 1);
    [[LJCMusicPlay shareMusicPlayer] seekToTime:dragTime completionHandler:^(BOOL finished) {
            [[LJCMusicPlay shareMusicPlayer] play];
            [LJCMusicPlay shareMusicPlayer].isPlay = NO;
    }];

}

/** 创建碟片 */
- (void)createDisc {
    _discView = [[LJCDiscView alloc] init];
    [self.view addSubview:_discView];
    [_discView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(180);
        make.centerX.equalTo(self.view.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(200, 200));
    }];
}

/** 播放进度监听 */
- (void)addProgressObserver {
    
    // CMTime 是专门计算视频的时间格式
    // Core Media
    // 参数1：设置监听的时间间隔
    [[LJCMusicPlay shareMusicPlayer] addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {

        [self getTime];
    }];
}
/** 计算时间 */
- (void)getTime {
    // 获取到总的视频时间
    CGFloat duration = [[LJCMusicPlay shareMusicPlayer] getDuration];
    // 获取到当前时间
    CGFloat current = [[LJCMusicPlay shareMusicPlayer] getCurrentTime];
    // 把总时间转化为字符串
    NSString *durationT = [NSString stringWithFormat:@"%02d:%02d", (int)duration/60, (int)duration%60];
    NSString *currentT = [NSString stringWithFormat:@"%02d:%02d", (int)current/60, (int)current%60];
    NSString *timeStr = [NSString stringWithFormat:@"%@/%@", currentT, durationT];
    self.timeLabel.text = timeStr;
    // 记录总时间
    self.totalDuration = duration;
    // slider的value
    self.progressSlider.value = current / duration;
    //图片旋转
//    _discView.imageView.transform = CGAffineTransformRotate(_discView.imageView.transform, M_PI/180);
    
}


#pragma mark - 生命周期方法

- (void)viewWillDisappear:(BOOL)animated {
    [LJCMusicSwitch shareMusicSwitch].hidden = NO;
    [[LJCMusicSwitch shareMusicSwitch] onOrOffMusic];
    [[LJCMusicSwitch shareMusicSwitch] openMusic];

    
}


- (void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBar.hidden = NO;
    LJCMusicModel *musicModel = _urlArr[_index];
    [self blackGroundView:musicModel.imgUrl];
    [_discView getImage:musicModel.imgUrl];
    [self isTransfer];
    [LJCMusicSwitch shareMusicSwitch].index = &(_index);
    [LJCMusicSwitch shareMusicSwitch].urlArr = _urlArr;
    [LJCMusicSwitch shareMusicSwitch].hidden = YES;
    
    
    LJCPlayerView *playButton = [self.view viewWithTag:2000];
    
    
    if ([LJCMusicPlay shareMusicPlayer].isPlay == NO) {
        [playButton.playButton setImage:[UIImage imageNamed:@"iconfont-zanting.png"] forState:UIControlStateNormal];
    } else {
        [playButton.playButton setImage:[UIImage imageNamed:@"iconfont-iconfontbofang.png"] forState:UIControlStateNormal];
    }

    
}

/** 毛玻璃 */
- (void)blackGroundView:(NSString *)imgUrl {

    NSURL *url = [NSURL URLWithString:imgUrl];
    
    NSData *data = [NSData dataWithContentsOfURL:url];
    
    UIImage *image = [[UIImage imageWithData:data] boxblurImageWithBlur:0.9];
    
    self.view.backgroundColor = [UIColor colorWithPatternImage:image];
    

}

/** 判断是否转 */
- (void)isTransfer {
    if ([LJCMusicPlay shareMusicPlayer].isPlay == YES) {
        [self stopImage];

    } else {
        [self playImage];

    }

}

- (void)stopImage {
    // 暂停
    CFTimeInterval stopTime = [_discView.imageView.layer convertTime:CACurrentMediaTime() fromLayer:nil];
    // 设置动画速度
    _discView.imageView.layer.speed = 0;
    // 保存时间的偏移量
    _discView.imageView.layer.timeOffset = stopTime;

}

- (void)playImage{
    CFTimeInterval stopTime = _discView.imageView.layer.timeOffset;
    
    // 速度设置为1
    _discView.imageView.layer.speed = 1;
    //
    _discView.imageView.layer.beginTime = 0;
    _discView.imageView.layer.timeOffset = 0;
    // 设置开始的时间
    _discView.imageView.layer.beginTime = [_discView.imageView.layer convertTime:CACurrentMediaTime() fromLayer:nil] - stopTime;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
